package com.syl.generator.common.api;

import com.syl.generator.common.api.bean.BaseBuild;
import com.syl.generator.common.constant.BaseConstant;
import com.syl.generator.common.util.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import org.apache.log4j.Logger;
import java.io.*;

/**
 * 业务模块的构建
 *
 * @author syl
 * @create 2018-03-24 01:10
 */
public class BiGenerator {
    private static final Logger LOG = Logger.getLogger(BiGenerator.class);

    public static final String DEFAULT_ENCODING = ConfigReadUtil.getYmlString("generate.encoding","UTF-8");

    /**
     * 生成方式 utf-8,不覆盖,默认存在即不生成
     * @param base BaseBuild
     */
    public BiGenerator(BaseBuild base){
        this(base, DEFAULT_ENCODING,false);
    }

    /**
     * 生成方式 utf-8
     * @param base BaseBuild
     * @param cover 是否覆盖  存在即不生成
     */
    public BiGenerator(BaseBuild base, boolean cover){
        this(base,DEFAULT_ENCODING,cover);
    }

    /**
     * 生成业务代码
     * @param base BaseBuild
     * @param encoding 编码
     * @param cover 是否覆盖  存在即不生成
     * @throws IOException
     * @throws TemplateException
     */
    public BiGenerator(BaseBuild base, String encoding, boolean cover){
        Configuration cfg = new Configuration(new Version(BaseConstant.FREEMARKER_VERSION));
        FileOutputStream fos = null;
        Writer out = null;
        try {
            String fileName = base.getTemplateFileName();
            File directoryFile = new File(base.getTemplateDirectory());
            LOG.info("模板文件:"+directoryFile.getPath()+File.separator+fileName);
            cfg.setDirectoryForTemplateLoading(directoryFile);
            Template template = cfg.getTemplate(fileName);
            File file = new File(base.getPath()+base.getFileName()+base.getFileType().getName());
            File temp = file.getParentFile();
            if(!temp.exists())temp.mkdirs();
            if(file.exists() && !cover)return;
            LOG.info("文件输出路径："+file.getPath());
            fos = new FileOutputStream(file);
            out = new OutputStreamWriter(fos, StringUtils.isEmpty(encoding) ? DEFAULT_ENCODING : encoding);
            template.process(base, out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }finally {
            try {
                if(out != null)out.close();
                if(fos != null)fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
